//
//  YCRegisterViewController.m
//  YCSchool
//
//  Created by gmall on 16/5/6.
//  Copyright © 2016年 yanglinxia. All rights reserved.
//  注册界面

#import "YCRegisterViewController.h"
#import "YCRegisterTextField.h"
#import "YCRegisterSuccessViewController.h"
#import "YCLoginUser.h"

@interface YCRegisterViewController ()<UITextFieldDelegate,UIGestureRecognizerDelegate,TTTAttributedLabelDelegate>
/** scrollView  */
@property (nonatomic, strong) UIScrollView *scrollView;
/** contentView  */
@property (nonatomic, strong) UIView *contentView;

///注册标题
@property (nonatomic,readonly) UILabel *registerLabel;
///我的名字
@property (nonatomic,readonly) YCRegisterTextField *usernameField;
///手机号码
@property (nonatomic,readonly) YCRegisterTextField *phoneField;
///设定密码
@property (nonatomic,readonly) YCRegisterTextField *setPasswordField;
///确定密码
@property (nonatomic,readonly) YCRegisterTextField *ensurePasswordField;
///提交按钮
@property (nonatomic,readonly) UIButton *commitButton;
///用户协议选中按钮
@property (nonatomic,readonly) UIButton *selectButton;
@property (nonatomic,readonly) UIButton *protocolBackgroudButton;
///用户协议文字
@property (nonatomic,readonly) TTTAttributedLabel *protocolLabel;
///返回
@property (nonatomic,readonly) UIButton *backButton;

/** 记录当前响应view转到window的frame  */
@property (nonatomic, assign) CGRect firstResponseViewFrameOfWindow;

@end

@implementation YCRegisterViewController

@synthesize registerLabel = _registerLabel;
@synthesize usernameField = _usernameField;
@synthesize phoneField = _phoneField;
@synthesize setPasswordField = _setPasswordField;
@synthesize ensurePasswordField = _ensurePasswordField;
@synthesize commitButton = _commitButton;
@synthesize selectButton = _selectButton;
@synthesize protocolBackgroudButton = _protocolBackgroudButton;
@synthesize protocolLabel = _protocolLabel;
@synthesize backButton = _backButton;

#pragma mark - 懒加载
// 用户注册
- (UILabel *)registerLabel
{
    if(!_registerLabel)
    {
        _registerLabel = [[UILabel alloc] init];
        _registerLabel.text = @"用户注册";
        _registerLabel.textColor = [UIColor yc_colorWithUInt:0x3d3e40];
        _registerLabel.textAlignment = NSTextAlignmentCenter;
        _registerLabel.font = [UIFont systemFontOfSize:24];
    }
    return _registerLabel;
}

// 我的名字
- (YCRegisterTextField *)usernameField
{
    if(!_usernameField)
    {
        _usernameField = [[YCRegisterTextField alloc] initWithLeftViewTitle:@"我的名字"];
        _usernameField.layer.cornerRadius= 17.5;
        _usernameField.layer.masksToBounds = YES;
        _usernameField.placeholder = NSLocalizedString(@"请输入您的名字", nil);//有默认颜色
        _usernameField.returnKeyType = UIReturnKeyNext;
        _usernameField.delegate = self;
    }
    return _usernameField;
}

- (YCRegisterTextField *)phoneField
{
    if(!_phoneField)
    {
        _phoneField = [[YCRegisterTextField alloc] initWithLeftViewTitle:@"手机号码"];
        _phoneField.layer.cornerRadius= 17.5;
        _phoneField.layer.masksToBounds = YES;
        _phoneField.keyboardType = UIKeyboardTypeNumberPad;
        _phoneField.placeholder = NSLocalizedString(@"输入您的手机号码", nil);//有默认颜色
        _phoneField.returnKeyType = UIReturnKeyNext;
        _phoneField.delegate = self;
    }
    return _phoneField;
}

- (YCRegisterTextField *)setPasswordField
{
    if(!_setPasswordField)
    {
        _setPasswordField = [[YCRegisterTextField alloc] initWithLeftViewTitle:@"设定密码"];
        _setPasswordField.layer.cornerRadius= 17.5;
        _setPasswordField.layer.masksToBounds = YES;
        _setPasswordField.secureTextEntry = YES;
        _setPasswordField.placeholder = NSLocalizedString(@"输入您要设定的密码", nil);//有默认颜色
        _setPasswordField.returnKeyType = UIReturnKeyNext;
        _setPasswordField.delegate = self;
    }
    return _setPasswordField;
}

- (YCRegisterTextField *)ensurePasswordField
{
    if(!_ensurePasswordField)
    {
        _ensurePasswordField = [[YCRegisterTextField alloc] initWithLeftViewTitle:@"确定密码"];
        _ensurePasswordField.layer.cornerRadius= 17.5;
        _ensurePasswordField.layer.masksToBounds = YES;
        _ensurePasswordField.secureTextEntry = YES;
        _ensurePasswordField.placeholder = NSLocalizedString(@"再次输入密码", nil);//有默认颜色
        _ensurePasswordField.returnKeyType = UIReturnKeyDone;
        _ensurePasswordField.delegate = self;
    }
    return _ensurePasswordField;
}

- (UIButton *)selectButton
{
    if(!_selectButton)
    {
        _selectButton = [[UIButton alloc] init];
        [_selectButton setImage:[UIImage imageNamed:@"已同意"] forState:UIControlStateSelected];
        [_selectButton setImage:[UIImage imageNamed:@"未同意"] forState:UIControlStateNormal];
        _selectButton.backgroundColor = [UIColor whiteColor];
        [_selectButton addTarget:self action:@selector(didTouchUpInsideSelectButton) forControlEvents:UIControlEventTouchUpInside];
        
    }
    return _selectButton;
}

- (UIButton *)protocolBackgroudButton
{
    if(!_protocolBackgroudButton)
    {
        _protocolBackgroudButton = [[UIButton alloc] init];
        _protocolBackgroudButton.backgroundColor = [UIColor clearColor];
        [_protocolBackgroudButton addTarget:self action:@selector(didTouchUpInsideSelectButton) forControlEvents:UIControlEventTouchUpInside];
        
    }
    return _protocolBackgroudButton;
}

- (TTTAttributedLabel *)protocolLabel
{
    if (!_protocolLabel) {
        NSString *msg = @"我已阅读并同意《用户协议》";
        _protocolLabel = [[TTTAttributedLabel alloc] initWithFrame:CGRectMake(0, 0, 200, 30)];
        _protocolLabel.delegate = self;
        _protocolLabel.textAlignment = NSTextAlignmentLeft;
        _protocolLabel.font = [UIFont systemFontOfSize:12];
        _protocolLabel.textColor = [UIColor yc_colorWithUInt:0x3d3e40];
        _protocolLabel.userInteractionEnabled = YES;
        _protocolLabel.linkAttributes = @{(NSString *)kCTForegroundColorAttributeName:[UIColor yc_colorWithUInt:0x007eff]};
        _protocolLabel.activeLinkAttributes = @{(NSString *)kCTForegroundColorAttributeName:[UIColor yc_colorWithUInt:0x3d3e40]};//按下时
        _protocolLabel.extendsLinkTouchArea = YES;
        _protocolLabel.verticalAlignment = TTTAttributedLabelVerticalAlignmentCenter;
        
        _protocolLabel.text = msg;
        [_protocolLabel addLinkToAddress:@{} withRange:NSMakeRange(msg.length - 6, 6)];
    }
    return _protocolLabel;
}

- (UIButton *)commitButton
{
    if(!_commitButton)
    {
        _commitButton = [[UIButton alloc] init];
        _commitButton.titleLabel.font = [UIFont boldSystemFontOfSize:15];
        [_commitButton setTitleColor:[UIColor yc_colorWithUInt:0x3d3e40] forState:UIControlStateNormal];
        _commitButton.backgroundColor = [UIColor yc_colorWithUInt:0xf8bb36];
        _commitButton.layer.cornerRadius = 17.5;
        [_commitButton setTitle:NSLocalizedString(@"提交", nil) forState:UIControlStateNormal];
        [_commitButton addTarget:self action:@selector(didTouchUpInsideCommitButton:) forControlEvents:UIControlEventTouchUpInside];
        
    }
    return _commitButton;
}

- (UIButton *)backButton
{
    if(!_backButton)
    {
        _backButton = [[UIButton alloc] init];
        _backButton.titleLabel.font = [UIFont systemFontOfSize:15];
        _backButton.backgroundColor = [UIColor yc_colorWithUInt:0x3d3e40];
        _backButton.layer.cornerRadius = 17.5;
        [_backButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_backButton setTitle:NSLocalizedString(@"返回", nil) forState:UIControlStateNormal];
        [_backButton addTarget:self action:@selector(didTouchUpInsideBackButton:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _backButton;
}

#pragma mark - 生命周期

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self yc_addBackBarButtonItem];
    self.view.backgroundColor = [UIColor yc_colorWithUInt:0xf7f7f7];
    [self makeView];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillChangeFrameNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveKeyboardWillChangeFrameNotification:) name:UIKeyboardWillChangeFrameNotification object:nil];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillChangeFrameNotification object:nil];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}


#pragma mark - 创建view

- (void)makeView
{
    self.scrollView = [[UIScrollView alloc] initWithFrame:self.view.bounds];
    self.scrollView.alwaysBounceVertical = YES;
    // 添加单击手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapScrollView:)];
    tap.delegate = self;
    [self.scrollView addGestureRecognizer:tap];
    [self.view addSubview:self.scrollView];
    self.scrollView.contentInset = UIEdgeInsetsMake(-20, 0, 0, 0);//UIEdgeInsetsMake(-64, 0, 0, 0);
    [self.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.bottom.equalTo(self.view);
    }];
    
    UIView *contentView = [[UIView alloc] init];
    contentView.backgroundColor = [UIColor yc_colorWithUInt:0xf7f7f7];
    self.contentView = contentView;
    [self.scrollView addSubview:contentView];
    [self.contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(self.scrollView);
        make.width.equalTo(self.scrollView);
    }];
    
    [self.contentView addSubview:self.registerLabel];
    [self.contentView addSubview:self.usernameField];
    [self.contentView addSubview:self.phoneField];
    [self.contentView addSubview:self.setPasswordField];
    [self.contentView addSubview:self.ensurePasswordField];
    [self.contentView addSubview:self.selectButton];
    [self.contentView addSubview:self.protocolLabel];
    [self.contentView addSubview:self.protocolBackgroudButton];
    [self.contentView addSubview:self.commitButton];
    [self.contentView addSubview:self.backButton];
    
    [_registerLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        
        [YCAdapter performOtherBlock:^{
            make.top.equalTo(self.contentView).offset(60);
        } IPhone6Block:^{
            make.top.equalTo(self.contentView).offset(111);
        } IPhone6pBlock:^{
            make.top.equalTo(self.contentView).offset(120);
        }];
        make.centerX.equalTo(self.contentView);
    }];
    
    [_usernameField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_registerLabel.mas_bottom).with.offset(heightFromIphone6Height(52));
        make.centerX.equalTo(self.contentView);
        make.left.equalTo(self.contentView).offset(47);
        make.right.equalTo(self.contentView).offset(-47);
        make.height.equalTo(@36);
    }];
    
    [_phoneField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_usernameField.mas_bottom).with.offset(heightFromIphone6Height(20));
        make.centerX.equalTo(self.contentView);
        make.left.equalTo(self.contentView).offset(47);
        make.right.equalTo(self.contentView).offset(-47);
        make.height.equalTo(@36);
    }];
    
    [_setPasswordField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_phoneField.mas_bottom).with.offset(heightFromIphone6Height(20));
        make.centerX.equalTo(self.contentView);
        make.left.equalTo(self.contentView).offset(47);
        make.right.equalTo(self.contentView).offset(-47);
        make.height.equalTo(@36);
    }];
    
    [_ensurePasswordField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_setPasswordField.mas_bottom).with.offset(heightFromIphone6Height(20));
        make.centerX.equalTo(self.contentView);
        make.left.equalTo(self.contentView).offset(47);
        make.right.equalTo(self.contentView).offset(-47);
        make.height.equalTo(@36);
    }];
    
    [_selectButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_ensurePasswordField.mas_bottom).with.offset(heightFromIphone6Height(30));
        make.left.equalTo(self.contentView).offset(widthFromIphone6Width(93));
        make.width.height.equalTo(@14);
    }];
    
    [_protocolLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(_selectButton);
        make.left.equalTo(_selectButton.mas_right).offset(10);
    }];
    
    CGFloat margin = [@"《用户协议》" yc_sizeWithFont:_protocolLabel.font MaxSize:CGSizeMake(CGFLOAT_MAX, 0)].width;
    [_protocolBackgroudButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.bottom.equalTo(_protocolLabel);
        make.right.equalTo(_protocolLabel).offset(-margin);
    }];
    
    
    [_commitButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_selectButton.mas_bottom).with.offset(heightFromIphone6Height(30));
        make.centerX.equalTo(self.contentView);
        make.left.equalTo(self.contentView).offset(47);
        make.right.equalTo(self.contentView).offset(-47);
        make.height.equalTo(@36);
    }];
    
    [_backButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_commitButton.mas_bottom).with.offset(heightFromIphone6Height(14));
        make.centerX.equalTo(self.contentView);
        make.left.equalTo(self.contentView).offset(47);
        make.right.equalTo(self.contentView).offset(-47);
        make.height.equalTo(@36);
    }];
    
    [self.contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(_backButton.mas_bottom).offset(heightFromIphone6Height(100));
    }];
    
    [self.view layoutIfNeeded];
    self.scrollView.contentSize = CGSizeMake(0, CGRectGetMaxY(self.contentView.frame)-64);//有导航条时要-64
}


#pragma mark -- 响应事件

///提交按钮
- (void)didTouchUpInsideCommitButton:(UIButton *)button
{
    if (self.usernameField.text.length == 0 ||
        self.phoneField.text.length == 0 ||
        self.setPasswordField.text.length == 0 ||
        self.ensurePasswordField.text.length == 0
        ) {
        [YCAlertView showMsg:@"每个选项都需要填写，不能为空"];
        return;
    }
    
    if (![self.phoneField.text validateMobile]) {
        [YCAlertView showMsg:@"请输入正确的手机号码"];
        return;
    };
    
    if (![self.setPasswordField.text isEqualToString:self.ensurePasswordField.text]) {
        [YCAlertView showMsg:@"两次密码不一致"];
        return;
    }
    
    if (!self.selectButton.isSelected) {
        [YCAlertView showMsg:@"请勾选我已阅读并同意用户协议"];
        return;
    }
    
    YCLog(@"提交");
    [self.view endEditing:YES];
    [SVProgressHUD showWithStatus:@"注册中..."];
    
    NSString *nickNameStr = _usernameField.text.length > 18 ? [[_usernameField.text substringToIndex:6] yc_trimString] : [_usernameField.text yc_trimString];
    NSString *phoneStr = [_phoneField.text yc_trimString];
    NSString *passwordStr = [[_setPasswordField.text yc_trimString] yc_md5String];
    
    NSDictionary *params = @{
                             @"nickname":nickNameStr,
                             @"mobile":phoneStr,
                             @"password":passwordStr,
                                 };
    [[YCNetworManager shareManager] postWithUrl:YCAPIRegisterCommit params:params success:^(NSURLSessionDataTask *task, ServiceResponse *response) {
        YCLog(@"响应消息--%@,响应内容:%@--",response.message,response.data);
        [SVProgressHUD dismiss];
        if ([@"此手机号码已经注册了" isEqualToString:response.message]) {
            [YCAlertView showMsg:@"此手机号码已经注册了"];
        } else {
            [SVProgressHUD showSuccessWithStatus:@"注册成功"];
        }
        YCLoginUser *userModel = [YCLoginUser yc_objectWithKeyValues:response.data];
        userModel.userMobilPhone = phoneStr;
        [self.navigationController pushViewController:[[YCRegisterSuccessViewController alloc] initWithUserModel:userModel] animated:YES];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        YCLog(@"%@",error.localizedDescription);
        [SVProgressHUD dismiss];
    }];
    
}

///选中我已阅读并同意...
- (void)didTouchUpInsideSelectButton
{
    YCLogFunc
    self.selectButton.selected = !self.selectButton.isSelected;
}

///返回按钮
- (void)didTouchUpInsideBackButton:(UIButton *)button
{
    YCLogFunc
    [self.navigationController popViewControllerAnimated:YES];
}

///点击回弹键盘
- (void)tapScrollView:(UITapGestureRecognizer *)tap
{
    YCLogFunc
    [self.view endEditing:YES];
    [UIView animateWithDuration:0.25 animations:^{
        self.view.bounds = CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds));
    }];
}

#pragma mark - UITextField delegate

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self.view endEditing:YES];
    return YES;
}


#pragma mark - 通知回调
///键盘将要弹出通知回调
- (void)receiveKeyboardWillChangeFrameNotification:(NSNotification *)notification
{
    CGRect rect = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    NSTimeInterval duration = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    // 获取当前第一响应view
    UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
    UIView *firstResponseView = [keyWindow performSelector:@selector(firstResponder)];
    
    _firstResponseViewFrameOfWindow = [self.view convertRect:firstResponseView.frame toView:keyWindow];
    if(rect.origin.y < kScreenHeight)//键盘上弹了
    {
        CGFloat offset = CGRectGetMaxY(_firstResponseViewFrameOfWindow) - CGRectGetMinY(rect)+15;//高出15
        if(offset < 0 ) return;
        rect = self.view.bounds;
        rect.origin.y = (offset);
        [UIView animateWithDuration:duration animations:^{
            self.view.bounds = rect;
        }];
    }
    else
    {
        [UIView animateWithDuration:duration animations:^{
            self.view.bounds = CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds));
        }];
    }
}

#pragma mark  - 手势代理
/// 解决手势冲突
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    if ([touch.view isKindOfClass:[TTTAttributedLabel class]]){
        TTTAttributedLabel *label = (TTTAttributedLabel *)touch.view;
        if ([label containslinkAtPoint:[touch locationInView:label]]){
            return NO;
        }else{
            return YES;
        }
    }else{
        return YES;
    }
}

#pragma mark - TTTAttributedLabel delegate

- (void)attributedLabel:(TTTAttributedLabel *)label
didSelectLinkWithAddress:(NSDictionary *)addressComponents
{
    YCLog(@"在这里加载用户协议");
    YCWebViewController *usVC = [[YCWebViewController alloc] initWithURLString:@"http://ios.legacy.hk:8899/myapp/xieyi.html"];
    [self.navigationController pushViewController:usVC animated:YES];
}
@end
